'use strict';

const nodemailer = require('nodemailer');
const config = require('../config');
const { info: loggerInfo, error: loggerError, color } = require('./logger.utils');

class EmailTool {
    constructor() {
        this.transporter = null;
        this.isInit = false;
    }

    // 改为异步初始化，避免阻塞服务启动
    async initTransporter() {
        if (this.isInit) return true;
        try {
            const { email } = config;

            // 修复：从配置读取SMTP信息，支持多服务商
            const smtpConfig = {
                service: email.email_service,
                port: email.email_service === 'qq' ? 465 : 587,
                secure: email.email_service === 'qq' ? true : false,
                auth: {
                    user: email.email_user,
                    pass: email.email_pass,
                },
                tls: { rejectUnauthorized: false },
            };

            this.transporter = nodemailer.createTransport(smtpConfig);
            await this.transporter.verify(); // 改为异步校验
            loggerInfo(`${color.green}📧 邮件服务初始化成功！发件人：${email.email_user}${color.reset}`);
            this.isInit = true;
            return true;
        } catch (err) {
            loggerError(`${color.red}❌ 邮件工具初始化异常：${err.message}${color.reset}`);
            this.isInit = false;
            return false;
        }
    }

    // 新增：发送前检查并自动重连
    async checkAndReconnect() {
        if (!this.isInit || !this.transporter) {
            return await this.initTransporter();
        }
        return true;
    }

    async sendVerifyCode(to, code, type = 'register') {
        if (!to || !code) {
            loggerError(`${color.red}❌ 验证码邮件参数缺失：收件人/验证码不能为空${color.reset}`);
            return false;
        }

        // 发送前检查连接
        if (!(await this.checkAndReconnect())) return false;

        const subjectMap = {
            register: '【CorpHR】注册验证码',
            reset: '【CorpHR】密码重置验证码',
        };
        const subject = subjectMap[type] || subjectMap.register;
        const sender = `"CorpHR系统" <${config.email.email_user}>`;

        const html = `
          <div style="max-width: 600px; margin: 0 auto; padding: 20px; font-family: sans-serif;">
            <h2 style="color: #2d3748; text-align: center;">${subject}</h2>
            <div style="background: #f5fafe; padding: 30px; border-radius: 8px; text-align: center;">
              <p style="font-size: 16px; color: #4a5568; margin: 0 0 20px;">您的验证码为：</p>
              <div style="font-size: 24px; font-weight: bold; color: #4299e1; letter-spacing: 8px;">${code}</div>
              <p style="font-size: 12px; color: #ff4d4f; margin: 20px 0 0;">⚠️ 验证码5分钟内有效，请勿泄露给他人</p>
            </div>
            <p style="font-size: 12px; color: #718096; text-align: center; margin-top: 20px;">
              若不是您操作，请忽略此邮件
            </p>
          </div>
        `;

        try {
            const startTime = Date.now();
            await this.transporter.sendMail({
                from: sender,
                to,
                subject,
                html,
                messageId: `<${Date.now()}-${Math.random().toString(36).substr(2, 9)}@${email.email_service}.com>`,
            });
            const costTime = Date.now() - startTime;
            loggerInfo(
                `${color.green}✅ 验证码邮件发送成功${color.reset} | 发件人：${config.email.email_user} | 收件人：${to} | 耗时：${costTime}ms`,
            );
            return true;
        } catch (err) {
            loggerError(`${color.red}❌ 验证码邮件发送失败${color.reset} | 收件人：${to} | 原因：${err.message}`);
            this.isInit = false; // 标记连接失效，下次发送自动重连
            return false;
        }
    }

    async sendNotice(to, subject, content) {
        if (!to || !subject || !content) {
            loggerError(`${color.red}❌ 通知邮件参数缺失${color.reset}`);
            return false;
        }

        if (!(await this.checkAndReconnect())) return false;

        const sender = `"CorpHR系统" <${config.email.email_user}>`;
        const html = `
          <div style="max-width: 600px; margin: 0 auto; padding: 20px; font-family: sans-serif;">
            <h2 style="color: #2d3748; text-align: center;">${subject}</h2>
            <div style="padding: 20px; border: 1px solid #e8f4f8; border-radius: 8px;">
              <p style="font-size: 16px; color: #4a5568;">${content}</p>
            </div>
            <p style="font-size: 12px; color: #718096; text-align: center; margin-top: 20px;">
              CorpHR企业人力资源管理系统 © ${new Date().getFullYear()}
            </p>
          </div>
        `;

        try {
            const startTime = Date.now();
            await this.transporter.sendMail({ from: sender, to, subject, html });
            const costTime = Date.now() - startTime;
            loggerInfo(
                `${color.green}✅ 通知邮件发送成功${color.reset} | 收件人：${to} | 主题：${subject} | 耗时：${costTime}ms`,
            );
            return true;
        } catch (err) {
            loggerError(`${color.red}❌ 通知邮件发送失败${color.reset} | 收件人：${to} | 原因：${err.message}`);
            this.isInit = false;
            return false;
        }
    }
}

module.exports = new EmailTool();
